package com.youbug.kefu.service.impl;

import cn.hutool.crypto.symmetric.AES;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.youbug.kefu.constant.MenuConstant;
import com.youbug.kefu.entity.Menu;
import com.youbug.kefu.entity.RoleMenu;
import com.youbug.kefu.entity.User;
import com.youbug.kefu.entity.UserRole;
import com.youbug.kefu.service.*;
import com.youbug.kefu.util.MenuUtils;
import com.youbug.kefu.vo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class LoginService implements ILoginService {

    @Autowired
    private IUserService userService;
    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private IRoleMenuService roleMenuService;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private AES aes;
    @Override
    public UserInfo login(User user) {

        UserInfo userInfo = new UserInfo();

        User userDb = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));

        Assert.isTrue(aes.decryptStr(userDb.getPassword()).equals(user.getPassword()), "用户名或密码错误");
        //查询用户所有角色
        List<UserRole> userRoles = userRoleService.list(new QueryWrapper<UserRole>().eq("user_id", userDb.getId()));

        List<Long> rolelds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());

        Assert.notEmpty(rolelds,"没有配置角色");

            List<RoleMenu> roleMenus = roleMenuService.list(new QueryWrapper<RoleMenu>().in("role_id", rolelds));

            List<Long> menuIds = roleMenus.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());

            Assert.notEmpty(menuIds,"角色没有对应的功能菜单");

            List<Menu> menus = menuService.list(new QueryWrapper<Menu>().in("id", menuIds));

            List<String> paths = menus.stream().filter(m -> MenuConstant.PAGE == m.getNodeType()).map(m->m.getPath().substring(1)).collect(Collectors.toList());

            request.getSession().setAttribute("permission", paths);

            List<Menu> menusTree = MenuUtils.makeMenuTree(menus, 0L);

            userInfo.setMenu(menusTree);

            userInfo.setUser(userDb);

            request.getSession().setAttribute("currentUser", user);
        return userInfo;
    }

}
